package service

import (
	"sync"
	"time"

	"gitee.com/liumou_site/go-network-monitoring/types"
	"gitee.com/liumou_site/go-network-monitoring/utils"
)

// ProcessMonitorInterface 进程监控服务接口
type ProcessMonitorInterface interface {
	GetProcessConnections() ([]types.ProcessConnection, error)
	GetProcessStats(pid int32) (*types.ProcessInfo, error)
	GetAllProcessStats() ([]types.ProcessInfo, error)
	Update() error
	GetLastUpdate() time.Time
	StartAutoUpdate(interval time.Duration)
}

// ProcessMonitorService 进程监控服务管理器
type ProcessMonitorService struct {
	monitor ProcessMonitorInterface
	mu      sync.RWMutex
}

var (
	globalProcessMonitor *ProcessMonitorService
	processMonitorOnce   sync.Once
)

// NewProcessMonitorService 创建进程监控服务
func NewProcessMonitorService() *ProcessMonitorService {
	service := &ProcessMonitorService{
		monitor: NewProcessNetworkService(), // Linux平台专用
	}
	// 进程监控默认启用，启动自动更新
	if service.monitor != nil {
		service.monitor.StartAutoUpdate(2 * time.Second)
	}
	return service
}

// GetGlobalProcessMonitor 获取全局进程监控服务实例
func GetGlobalProcessMonitor() *ProcessMonitorService {
	processMonitorOnce.Do(func() {
		globalProcessMonitor = NewProcessMonitorService()
	})
	return globalProcessMonitor
}

// GetProcessConnections 获取所有进程的连接信息
func (pms *ProcessMonitorService) GetProcessConnections() ([]types.ProcessConnection, error) {
	pms.mu.RLock()
	defer pms.mu.RUnlock()
	if pms.monitor != nil {
		return pms.monitor.GetProcessConnections()
	}
	return []types.ProcessConnection{}, nil
}

// GetProcessStats 获取指定进程的网络统计
func (pms *ProcessMonitorService) GetProcessStats(pid int32) (*types.ProcessInfo, error) {
	pms.mu.RLock()
	defer pms.mu.RUnlock()
	if pms.monitor != nil {
		return pms.monitor.GetProcessStats(pid)
	}
	return nil, nil
}

// GetAllProcessStats 获取所有进程的统计信息
func (pms *ProcessMonitorService) GetAllProcessStats() ([]types.ProcessInfo, error) {
	pms.mu.RLock()
	defer pms.mu.RUnlock()
	if pms.monitor != nil {
		return pms.monitor.GetAllProcessStats()
	}
	return []types.ProcessInfo{}, nil
}

// GetLastUpdate 获取最后更新时间
func (pms *ProcessMonitorService) GetLastUpdate() time.Time {
	pms.mu.RLock()
	defer pms.mu.RUnlock()
	if pms.monitor != nil {
		return pms.monitor.GetLastUpdate()
	}
	return time.Time{}
}

// Update 手动更新进程监控数据
func (pms *ProcessMonitorService) Update() error {
	pms.mu.RLock()
	defer pms.mu.RUnlock()
	if pms.monitor != nil {
		return pms.monitor.Update()
	}
	return nil
}

// 移除旧的方法，使用新的数据模型

// BuildProcessMonitoringStats 构建新的进程监控统计数据
func (pms *ProcessMonitorService) BuildProcessMonitoringStats(processes []types.ProcessInfo, connections []types.ProcessConnection) *types.ProcessMonitoringStats {
	stats := types.NewProcessMonitoringStats()
	
	// 基础统计
	stats.TotalProcesses = len(processes)
	for _, proc := range processes {
		if proc.IsAlive {
			stats.ActiveProcesses++
		}
		// 这里需要区分系统进程和用户进程，简化处理
		stats.UserProcesses++
	}
	stats.SystemProcesses = stats.TotalProcesses - stats.UserProcesses
	
	// 连接统计
	stats.TotalConnections = len(connections)
	for _, conn := range connections {
		switch conn.Protocol {
		case "TCP":
			stats.TCPConnections++
		case "UDP":
			stats.UDPConnections++
		}
		
		switch conn.Status {
		case "LISTEN":
			stats.ListeningPorts++
		case "ESTABLISHED":
			stats.EstablishedConns++
		case "CLOSE_WAIT":
			stats.CloseWaitConns++
		case "TIME_WAIT":
			stats.TimeWaitConns++
		}
	}
	
	// 流量统计
	for _, proc := range processes {
		stats.TotalBytesSent += proc.TotalSent
		stats.TotalBytesRecv += proc.TotalRecv
		stats.CurrentSpeedUp += proc.SpeedUp * 1024 * 1024 / 8  // 转换为B/s
		stats.CurrentSpeedDown += proc.SpeedDown * 1024 * 1024 / 8 // 转换为B/s
	}
	
	// 格式化字符串
	stats.TotalTrafficSentText = utils.FormatBytes(stats.TotalBytesSent)
	stats.TotalTrafficRecvText = utils.FormatBytes(stats.TotalBytesRecv)
	stats.CurrentSpeedUpText = utils.FormatSpeed(stats.CurrentSpeedUp)
	stats.CurrentSpeedDownText = utils.FormatSpeed(stats.CurrentSpeedDown)
	
	return stats
}

// GetNetworkConnectionDetails 获取网络连接明细数据
func (pms *ProcessMonitorService) GetNetworkConnectionDetails() ([]types.NetworkConnectionDetail, error) {
	connections, err := pms.GetProcessConnections()
	if err != nil {
		return nil, err
	}
	
	var details []types.NetworkConnectionDetail
	for _, conn := range connections {
		detail := types.NetworkConnectionDetail{
				ConnectionID:     utils.GenerateConnectionID(conn),
				Protocol:         conn.Protocol,
				Status:           conn.Status,
				LocalAddr:        conn.LocalAddr,
				LocalPort:        conn.LocalPort,
				LocalPortText:    utils.FormatPort(conn.LocalPort),
				RemoteAddr:       conn.RemoteAddr,
				RemotePort:       conn.RemotePort,
				RemotePortText:   utils.FormatPort(conn.RemotePort),
				PID:              conn.PID,
				ProcessName:      conn.ProcessName,
				Executable:       "", // 从ProcessInfo获取
				Username:         "", // 从ProcessInfo获取
				BytesSent:        conn.BytesSent,
				BytesReceived:    conn.BytesRecv,
				BytesTotal:       conn.BytesSent + conn.BytesRecv,
				BytesSentText:    utils.FormatBytes(conn.BytesSent),
				BytesReceivedText: utils.FormatBytes(conn.BytesRecv),
				BytesTotalText:   utils.FormatBytes(conn.BytesSent + conn.BytesRecv),
				IsListening:      conn.Status == "LISTEN",
				IsEstablished:    conn.Status == "ESTABLISHED",
				Direction:        utils.GetConnectionDirection(conn.RemoteAddr),
				CreatedAt:        time.Now().Format("2006-01-02 15:04:05"),
				LastActivity:     time.Now().Format("2006-01-02 15:04:05"),
				Duration:         "刚刚",
			}
		details = append(details, detail)
	}
	
	return details, nil
}

// GetProcessDetails 获取进程明细数据
func (pms *ProcessMonitorService) GetProcessDetails() ([]types.ProcessDetail, error) {
	processes, err := pms.GetAllProcessStats()
	if err != nil {
		return nil, err
	}
	
	connections, err := pms.GetProcessConnections()
	if err != nil {
		return nil, err
	}
	
	var details []types.ProcessDetail
	for _, proc := range processes {
		detail := types.NewProcessDetail(proc.PID)
		
		// 基础信息
		detail.ProcessName = proc.ProcessName
		detail.Executable = proc.Executable
		detail.Username = proc.Username
		detail.Status = "running"
		detail.IsAlive = proc.IsAlive
		detail.HasNetworkActivity = proc.TotalConnections > 0
		
		// 网络活动
		detail.NetworkConnections = proc.TotalConnections
		detail.TCPConnections = proc.ActiveTCP
		detail.UDPConnections = proc.ActiveUDP
		detail.ListeningPorts = len(proc.ListeningPorts)
		
		// 流量统计
		detail.TotalBytesSent = proc.TotalSent
		detail.TotalBytesRecv = proc.TotalRecv
		detail.CurrentSpeedUp = proc.SpeedUp * 1024 * 1024 / 8
		detail.CurrentSpeedDown = proc.SpeedDown * 1024 * 1024 / 8
		
		// 收集端口和地址信息
		var localPorts []int
		var remoteAddrs []string
		for _, conn := range connections {
			if conn.PID == proc.PID {
				localPorts = append(localPorts, conn.LocalPort)
				if conn.RemoteAddr != "" && conn.RemoteAddr != "0.0.0.0" {
					remoteAddrs = append(remoteAddrs, conn.RemoteAddr)
				}
			}
		}
		detail.LocalPorts = utils.UniqueInts(localPorts)
		detail.RemoteAddrs = utils.UniqueStrings(remoteAddrs)
		
		// 格式化字符串
		detail.TotalTrafficText = utils.FormatBytes(proc.TotalSent + proc.TotalRecv)
		detail.CurrentSpeedUpText = utils.FormatSpeed(detail.CurrentSpeedUp)
		detail.CurrentSpeedDownText = utils.FormatSpeed(detail.CurrentSpeedDown)
		detail.StartTimeText = "未知"
		
		details = append(details, *detail)
	}
	
	return details, nil
}
